package service

import (
	"gitee.com/sansaniot/ssiot-core/sdk/msg/sms"
	"gitee.com/sansaniot/ssiot-core/sdk/service"
	"gorm.io/gorm"

	"ssnotification/common/dto"
	"ssnotification/common/enums/sendway"
	"ssnotification/internal/notify/models"
	"ssnotification/internal/notify/models/command"
	"ssnotification/internal/notify/models/query"
)

type NotifyTemplate struct {
	notifyTemplate *models.NotifyTemplate
	service.Service
}

func (e *NotifyTemplate) SetNotifyTemplateModel(m *models.NotifyTemplate) *NotifyTemplate {
	e.notifyTemplate = m
	return e
}

func (e *NotifyTemplate) AddNotifyTemplate(req *command.NotifyTemplateAddReq) (one models.NotifyTemplate, err error) {
	req.Generate(&one)
	err = e.Orm.Transaction(func(tx *gorm.DB) error {
		e.notifyTemplate.Orm = tx
		if req.Type == sendway.ShortMsg.Get().SendType {
			if er := sms.AddTemplate(&sms.Template{
				TemplateName:    &req.Name,
				TemplateContent: &req.Content,
			}); er != nil {
				return er
			}
		}
		if er := e.notifyTemplate.Upsert(&one); er != nil {
			return er
		}
		return nil
	})
	return
}

func (e *NotifyTemplate) EditNotifyTemplate(req *command.NotifyTemplateModReq) (err error) {
	if req.Type == sendway.ShortMsg.Get().SendType {
		return
	}
	if err = e.notifyTemplate.FindOne(e.notifyTemplate, dto.MakeCondition(query.NotifyTemplateGetReq{Id: req.Id})); err != nil {
		return
	}
	req.Generate(e.notifyTemplate)
	err = e.notifyTemplate.Mod(e.notifyTemplate)
	return
}

func (e *NotifyTemplate) DeleteNotifyTemplate(c *command.NotifyTemplateDelReq) (err error) {
	condition := dto.MakeCondition(query.NotifyTemplateGetReq{IdIn: c.Ids})
	notifyTemplates := make([]models.NotifyTemplate, 0)
	if err = e.notifyTemplate.FindList(&notifyTemplates, condition); err != nil {
		return
	}
	for _, v := range notifyTemplates {
		if v.Type == sendway.ShortMsg.Get().SendType {
			if er := sms.DeleteTemplate(v.Id); er != nil {
				e.Log.Error(er)
			}
		}
	}
	return e.notifyTemplate.Delete(e.notifyTemplate, condition)
}
